package com.motorola.dp.jenkinsmonitor.service.util.xml;

import javax.annotation.PostConstruct;

import org.apache.xerces.parsers.DOMParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import com.motorola.dp.jenkinsmonitor.model.util.ResponseInputStream;

@Service("xmlParsingService")
public class DefaultXmlParsingService implements XmlParsingService {

    @Value("#{new org.apache.xerces.parsers.DOMParser()}")
    private DOMParser xmlParser;

    @Value("#{new org.cyberneko.html.parsers.DOMParser()}")
    private DOMParser htmlParser;

    @PostConstruct
    public void afterPropertiesSet() throws Exception {
        xmlParser.setFeature("http://xml.org/sax/features/validation", false);
        xmlParser.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        xmlParser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

        htmlParser.setFeature("http://xml.org/sax/features/validation", false);
    }

    public Document parse(ResponseInputStream responseInputStream) throws Exception {
        InputSource source = new InputSource(responseInputStream.getInputStream());
        if (responseInputStream.isHtml()) {
            htmlParser.parse(source);
            return htmlParser.getDocument();
        } else {
            xmlParser.parse(source);
            return xmlParser.getDocument();
        }
    }

    public void setXmlParser(DOMParser xmlParser) {
        this.xmlParser = xmlParser;
    }

    public void setHtmlParser(DOMParser htmlParser) {
        this.htmlParser = htmlParser;
    }
}